<?php


class Db2
{
    protected static $pdo = null;
    protected $dsn;
    protected $username;
    protected $password;

    /**
     * Db2 constructor.
     * @param $dsn
     * @param $username
     * @param $password
     */
    private function __construct($dsn, $username, $password)
    {
        $this->dsn = $dsn;
        $this->username = $username;
        $this->password = $password;
        try {
            self::$pdo = new \PDO($this->dsn, $this->username, $this->password);
            self::$pdo->exec('set names utf8');
            // 数据库字段类型是什么，查出来的类型就是什么
            self::$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES,false);
        } catch (\Exception $e) {
            die('数据库连接失败: '.$e->getMessage());
        }
    }

    public static function getInstance($dsn = 'mysql:host=demo.com;dbname=demo', $user = 'root', $pass = 'root'){
        if (self::$pdo === null){
            new self($dsn, $user, $pass);
        }
        return self::$pdo;
    }

    private function __clone()
    {
    }
}